package org.example.demo;

/**
 * @Description
 * @Author chenhs
 * @Date 18:00 2025/7/26
 */
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JjwtDemo {

    // 安全密钥，实际项目中应该从配置中读取
//    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    private static final String BASE64_KEY = "Qi5WbesaqmucY42E0EEb8M5IZm/nNetI2an8BGObtMs=";
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(
            Decoders.BASE64.decode(BASE64_KEY)
    );
    // JWT有效期（毫秒）
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    public static void main(String[] args) {
        // 1. 创建JWT
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiYWRtaW4iLCJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyMTIzIiwiaWF0IjoxNzUzNTMzMjc0LCJleHAiOjE3NTM2MTk2NzR9.dqiQFdpAEWLMC4DxqD0ytAKFQyyLlEaq1xy2Z1K7VS8";
//        String token = createJwt("user123");
        System.out.println("Generated JWT: " + token);

        // 2. 解析JWT
        Claims claims = parseJwt(token);
        System.out.println("JWT Claims: " + claims);

        // 3. 验证JWT
        boolean isValid = validateJwt(token);
        System.out.println("Is JWT valid? " + isValid);
    }

    /**
     * 创建JWT
     * @param username 用户名
     * @return JWT字符串
     */
    public static String createJwt(String username) {
        System.out.println("Generated key (Base64): " + Encoders.BASE64.encode(SECRET_KEY.getEncoded()));

        // 设置JWT Claims
        Map<String, Object> claims = new HashMap<>();
        claims.put("role", "admin");
        claims.put("email", "user@example.com");

        // 生成JWT
        return Jwts.builder()
                .setClaims(claims)                      // 自定义claims
                .setSubject(username)                  // 主题
                .setIssuedAt(new Date())               // 签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // 过期时间
                .signWith(SECRET_KEY)                  // 签名算法和密钥
                .compact();
    }

    /**
     * 解析JWT
     * @param token JWT字符串
     * @return Claims对象
     */
    public static Claims parseJwt(String token) {
        System.out.println("parseJwt key (Base64): " + Encoders.BASE64.encode(SECRET_KEY.getEncoded()));

        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 验证JWT
     * @param token JWT字符串
     * @return 是否有效
     */
    public static boolean validateJwt(String token) {
        try {
            // 在验证Token前打印当前使用的密钥
            System.out.println("Current verification key (Base64): " + Encoders.BASE64.encode(SECRET_KEY.getEncoded()));

            Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            // 可以更详细地处理不同的异常
            // 如ExpiredJwtException, MalformedJwtException等
            return false;
        }
    }
}
